package cn.tedu.csmall.passportbackup.security;

import cn.tedu.csmall.passportbackup.ex.ServiceException;
import cn.tedu.csmall.passportbackup.mapper.AdminMapper;
import cn.tedu.csmall.passportbackup.pojo.vo.AdminLoginInfoVO;
import cn.tedu.csmall.passportbackup.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    public UserDetailsServiceImpl() {
       log.debug("开始处理UserDetailsServiceImpl");
    }

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("开始根据用户名：【{}】从数据库当中查询管理员信息",s);

        //调用AdminMapper对象，根据用户名查询管理员信息
        AdminLoginInfoVO loginInfoVO = adminMapper.getLoginInfoByUsername(s);
        //检查用户是否存在
        if(loginInfoVO == null){
            String message = "登录失败，此用户没有注册";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("根据用户名【{}】查询到有效的数据：{}",s,loginInfoVO);

        //从返回结果当中查询权限信息
        List<String> permissions = loginInfoVO.getPermission();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }


        //准备返回数据
        AdminDetails adminDetail = new AdminDetails(loginInfoVO.getUsername(),loginInfoVO.getPassword(),
                loginInfoVO.getEnable() == 1, authorities);
        adminDetail.setId(loginInfoVO.getId());
        log.debug("即将向Spring Security返回UserDetails：{}",adminDetail);
        return adminDetail;
    }
}
